<script setup>
import { ref, onMounted } from 'vue'
import api from '@/api/order.js'
// import paymentsApi from '@/api/payments_api.js'
import {ElMessage, ElMessageBox} from 'element-plus'

// 定义响应式数据
const orders = ref([]) // 订单列表数据
const loading = ref(false) // 加载状态
const total=ref(0);
//绑定查询数据
const searchObj=ref({
  current:1,
  size:10,
  orderId:'',
  paymentSn:'',
  payMethod:'',
  payAmount:'',
  payTime:''
});

//定义方法
const handleSizeChange=()=>{
  fetchOrders();
}
const handleCurrentChange=()=>{
  fetchOrders();
}

/**
 * 获取订单列表
 */
const fetchOrders = async () => {
  try {
    loading.value = true
    const res = await api.page(searchObj.value);
    orders.value = res.data;
    console.log(res);
    total.value=res.count;
  } catch (error) {
    ElMessage.error('获取订单失败')
  } finally {
    loading.value = false
  }
}

/**
 * 获取订单状态信息
 * @param {String} status 订单状态
 * @returns {Object} 包含状态文本和颜色的对象
 */
const getStatusInfo = (status) => {
  // 状态映射表
  const statusMap = {
    'pending': { text: '待付款', color: '#ffb703' },
    'paid': { text: '已支付', color: '#4361ee' },
    // 'shipped': { text: '已发货', color: '#4cc9f0' },
    'completed': { text: '已完成', color: '#2ec4b6' },
    'cancelled': { text: '已取消', color: '#f72585' }
  }
  return statusMap[status] || { text: '未知状态', color: '#adb5bd' }
}

//立即支付订单
const payOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
        `确定要支付订单 ${order.order_number} 吗？支付金额：¥${order.total_amount}`,
        '确认支付',
        {
          confirmButtonText: '确认支付',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    // 获取支付方式
    const payMethod = 'alipay';

    // 调用支付API
    const res = await api.payOrder({
      orderId: order.order_id, // 订单ID
      payMethod: payMethod     // 支付方式
    });

    // 更新订单状态
    order.status = 'paid'
    ElMessage.success('支付成功！')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('支付失败：' + (error.message || '未知错误'))
    }
  }
}

//确认收货
const confirmReceive = async (order) => {
  try {
    await ElMessageBox.confirm(
        `确定已收到订单 ${order.order_number} 的商品吗？`,
        '确认收货',
        {
          confirmButtonText: '确认收货',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
    // 调用确认收货API
    // await api.confirmReceive(order.order_id)

    // 更新订单状态
    order.status = 'completed'

    ElMessage.success('确认收货成功！')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('确认收货失败：' + (error.message || '未知错误'))
    }
  }
}

//取消订单
const cancelOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
        `确定要取消订单 ${order.order_number} 吗？`,
        '取消订单',
        {
          confirmButtonText: '确认取消',
          cancelButtonText: '继续支付',
          type: 'warning',
        }
    )

    // 调用取消订单API
    // await api.cancelOrder(order.order_id)

    // 更新订单状态
    order.status = 'cancelled'

    ElMessage.success('订单已取消！')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败：' + (error.message || '未知错误'))
    }
  }
}

// 组件挂载时获取订单数据
onMounted(() => {
  fetchOrders()
})
</script>

<template>
  <div class="orders-container">
    <h1 class="page-title">我的订单</h1>

    <!-- 空订单状态 -->
    <div v-if="total==0" class="empty-orders">
      <el-empty description="暂无订单记录">
        <el-button type="primary" @click="$router.push('/concert_show')">去抢票</el-button>
      </el-empty>
    </div>

    <!-- 订单列表 -->
    <div v-else class="orders-list">
      <!-- 遍历订单列表 -->
      <div
          v-for="order in orders"
          :key="order.orderId"
          class="order-card">
        <!-- 订单头部信息 -->
        <div class="order-header">
          <div class="order-id">订单编号: {{ order.orderId }}</div>
<!--          <div class="order-date">{{ new Date(order.create_time).toLocaleString() }}</div>-->
        </div>

        <!-- 订单主体内容 -->
        <div class="order-body">
          <!-- 订单状态标签 -->
          <div class="order-status" :style="{ backgroundColor: getStatusInfo(order.status).color }">
            {{ getStatusInfo(order.status).text }}
          </div>

          <!-- 订单商品列表 -->
          <div class="order-items">
            <!-- 遍历订单商品 -->
            <div
                v-for="(item, index) in order.orderItemsList"
                :key="index"
                class="order-item"
            >
              <!-- 商品图片 -->
<!--              <el-image-->
<!--                  :src="item.product?item.product.img_url:''"-->
<!--                  fit="cover"-->
<!--                  class="item-image"-->
<!--              />-->
              <!-- 商品信息 -->
              <div class="item-info">
<!--                <h4>{{ item.product?item.product.name:'' }}</h4>-->
                <p>¥{{ item.orderSn?item.payAmount:0 }}</p>
              </div>
            </div>
          </div>
        </div>


        <!-- 订单底部信息 -->
        <div class="order-footer">
          <!-- 订单总计 -->
          <div class="order-total">
            共 {{ order.orderItemsList.reduce((sum, item) => sum + item.count, 0) }} 件商品
            合计: <span class="total-amount">¥{{ order.payAmount }}</span>
          </div>
          <!-- 订单操作按钮 -->
          <div class="order-actions">
            <!-- 待付款状态显示支付按钮 -->
            <template v-if="order.status === 'pending'">
              <el-button
                  type="danger"
                  size="small"
                  @click="cancelOrder(order)"
              >
                取消订单
              </el-button>
            <el-button
                v-if="order.status === 'pending'"
                type="primary"
                size="small"
                @click="payOrder(order)"
            >
              立即支付
            </el-button>
            </template>
            <!-- 已发货状态显示确认收货按钮 -->
<!--            <el-button-->
<!--                v-if="order.status === 'shipped'"-->
<!--                type="success"-->
<!--                size="small"-->
<!--            >-->
<!--              确认收货-->
<!--            </el-button>-->
              <!-- 已支付状态显示查看支付记录按钮 -->
              <el-button
                  v-if="order.status === 'paid'"
                  type="info"
                  size="small"
                  @click="$router.push('/paymentsUser')"
              >
                查看支付记录
              </el-button>
              <!-- 已完成状态显示再次购买按钮 -->
              <el-button
                  v-if="order.status === 'completed'"
                  type="primary"
                  size="small"
                  @click="$router.push('/productUser')"
              >
                再次购买
              </el-button>

              <!-- 已取消状态显示重新购买按钮 -->
              <el-button
                  v-if="order.status === 'cancelled'"
                  type="info"
                  size="small"
                  @click="$router.push('/productUser')"
              >
                重新购买
              </el-button>
            <!-- 查看详情按钮 -->
<!--            <el-button-->
<!--                type="info"-->
<!--                size="small"-->
<!--                @click="$router.push(`/orderDetail/${order.order_id}`)"-->
<!--            >-->
<!--              查看详情-->
<!--            </el-button>-->
          </div>
        </div>
      </div>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="searchObj.current"
            v-model:page-size="searchObj.size"
            :page-sizes="[10, 20, 30, 40]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="pagination"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 订单容器样式 */
.orders-container {
  padding-top: 100px;
  max-width: 800px;
  margin: 0 auto;
}

/* 页面标题样式 */
.page-title {
  text-align: center;
  color: #4361ee;
  margin-bottom: 30px;
  font-size: 28px;
}

/* 空订单状态样式 */
.empty-orders {
  margin-top: 50px;
  text-align: center;
}

/* 订单列表样式 */
.orders-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 订单卡片样式 */
.order-card {
  background: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 订单头部样式 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
}

/* 订单ID样式 */
.order-id {
  font-weight: bold;
  color: #333;
}

/* 订单日期样式 */
.order-date {
  color: #666;
  font-size: 14px;
}

/* 订单主体样式 */
.order-body {
  padding: 20px;
}

/* 订单状态标签样式 */
.order-status {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 20px;
  color: white;
  font-size: 14px;
  margin-bottom: 15px;
}

/* 订单商品列表样式 */
.order-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 订单商品项样式 */
.order-item {
  display: flex;
  gap: 15px;
  align-items: center;
}

/* 商品图片样式 */
.item-image {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  object-fit: cover;
}

/* 商品信息样式 */
.item-info h4 {
  font-size: 15px;
  margin-bottom: 5px;
  color: #333;
}

.item-info p {
  color: #666;
  font-size: 14px;
}

/* 订单底部样式 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  background: #f8f9fa;
}

/* 订单总计样式 */
.order-total {
  font-size: 15px;
  color: #333;
}

/* 总计金额样式 */
.total-amount {
  font-weight: bold;
  color: #f72585;
  font-size: 18px;
}

/* 订单操作按钮区域样式 */
.order-actions {
  display: flex;
  gap: 10px;
}

/* 响应式设计 - 移动端适配 */
@media (max-width: 600px) {
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }

  .order-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .order-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>